#include "dxySocket.h"


namespace dxy::easyWebServer
{
DxySocket::DxySocket()
{

}

DxySocket::~DxySocket()
{

}

void DxySocket::init(const std::string & ip, uint16_t port)
{
    m_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(m_fd == -1) throw std::exception();

    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    int opt = 1;
    setsockopt(m_fd, SOL_SOCKET,SO_REUSEADDR,(const void *)&opt, sizeof(opt) );

    // setNoBlock(m_fd);

    bind(m_fd, (const struct sockaddr *)&addr, sizeof(addr));
    
    listen(m_fd, 5);

}

int DxySocket::socketAccept()
{
    int ret = accept(m_fd, nullptr, nullptr);
    if(ret == -1) throw std::exception();
    return ret;
}

int DxySocket::getfd()
{
    return m_fd;
}

}
